/* Gluten Library -- Window 
 *
 * A window, represents the entry point for most of the GLUT library.
 *
 * $AUTHOR$    res
 * $UPDATE$    r19
 */

/* LICENSES ********************************************************************

   Copyright (c) 2013- Reuben E. Smith

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.

*******************************************************************************/


// TODO Fix wheel click causing mouse entry events to fire.


#include <list>
#include <map>
#include <sstream>
#include "Window.hpp"


namespace Gluten
{
   typedef std::list<Window*> WindowList;
   typedef std::pair< int, int > MouseWheelDir;
   typedef std::map< int, MouseWheelDir > MouseWheelMap;

   WindowList windows;
   MouseWheelMap mouseWheels;


   Window::Window()
      : _windowID(0)
   {
   }


   Window::~Window()
   {
      destroy();
   }


   void Window::create(const std::string& title, unsigned int mode,
      int x, int y, unsigned int w, unsigned int h)
   {
      glutInitDisplayMode(mode);
      glutInitWindowPosition(x, y);
      glutInitWindowSize(static_cast<int>(w), static_cast<int>(h));
      _windowTitle = title;
      _windowID = glutCreateWindow(title.c_str());
      windows.push_back(this);

      glutCloseFunc(Window::windowClose);
      glutDisplayFunc(Window::windowDisplay);
      glutReshapeFunc(Window::windowReshape);
      glutKeyboardFunc(Window::windowKeyDown);
      glutKeyboardUpFunc(Window::windowKeyUp);
      glutSpecialFunc(Window::windowSKeyDown);
      glutSpecialUpFunc(Window::windowSKeyUp);
      glutEntryFunc(Window::windowMouseEntry);
      glutPassiveMotionFunc(Window::windowMouseMove);
      glutMotionFunc(Window::windowMouseDrag);
      glutMouseFunc(Window::windowMousePress);
      glutMouseWheelFunc(Window::windowMouseWheel);
      glutMenuStatusFunc(Window::windowMenu);

      onCreate();
   }


   void Window::destroy()
   {
      if (_windowID) {
         glutDestroyWindow(_windowID);
         _windowID = 0;
      }
   }


   int Window::getCursor() const
   {
      int result = GLUT_CURSOR_NONE;

      if (_windowID) {
         if (glutGetWindow() != _windowID) {
            glutPushWindow();
            glutSetWindow(_windowID);
            result = glutGet(GLUT_WINDOW_CURSOR);
            glutPopWindow();
         }
         else {
            result = glutGet(GLUT_WINDOW_CURSOR);
         }
      }

      return result;
   }


   void Window::setCursor(int cursor)
   {
      if (_windowID) {
         if (glutGetWindow() != _windowID) {
            glutPushWindow();
            glutSetWindow(_windowID);
            glutSetCursor(cursor);
            glutPopWindow();
         }
         else {
            glutSetCursor(cursor);
         }
      }
   }


   void Window::setKeyRepeat(bool state)
   {
      if (_windowID) {
         if (glutGetWindow() != _windowID) {
            glutPushWindow();
            glutSetWindow(_windowID);
            glutIgnoreKeyRepeat(state ? GL_FALSE : GL_TRUE);
            glutPopWindow();
         }
         else {
            glutIgnoreKeyRepeat(state ? GL_FALSE : GL_TRUE);
         }
      }
   }


   void Window::getPosition(int& x, int& y) const
   {
      if (_windowID) {
         if (glutGetWindow() != _windowID) {
            glutPushWindow();
            glutSetWindow(_windowID);
            x = glutGet(GLUT_WINDOW_X);
            y = glutGet(GLUT_WINDOW_Y);
            glutPopWindow();
         }
         else {
            x = glutGet(GLUT_WINDOW_X);
            y = glutGet(GLUT_WINDOW_Y);
         }
      }
   }


   void Window::setPosition(int x, int y)
   {
      if (_windowID) {
         if (glutGetWindow() != _windowID) {
            glutPushWindow();
            glutSetWindow(_windowID);
            glutPositionWindow(x, y);
            glutPopWindow();
         }
         else {
            glutPositionWindow(x, y);
         }
      }
   }


   void Window::getSize(unsigned int& w, unsigned int& h) const
   {
      if (_windowID) {
         if (glutGetWindow() != _windowID) {
            glutPushWindow();
            glutSetWindow(_windowID);
            w = static_cast<unsigned int>(glutGet(GLUT_WINDOW_WIDTH));
            h = static_cast<unsigned int>(glutGet(GLUT_WINDOW_HEIGHT));
            glutPopWindow();
         }
         else {
            w = static_cast<unsigned int>(glutGet(GLUT_WINDOW_WIDTH));
            h = static_cast<unsigned int>(glutGet(GLUT_WINDOW_HEIGHT));
         }
      }
   }


   void Window::setSize(unsigned int w, unsigned int h)
   {
      if (_windowID) {
         if (glutGetWindow() != _windowID) {
            glutPushWindow();
            glutSetWindow(_windowID);
            glutReshapeWindow(static_cast<int>(w), static_cast<int>(h));
            glutPopWindow();
         }
         else {
            glutReshapeWindow(static_cast<int>(w), static_cast<int>(h));
         }
      }
   }


   std::string Window::getTitle() const
   {
      return _windowTitle;
   }


   void Window::setTitle(const std::string& title)
   {
      if (_windowID) {
         if (glutGetWindow() != _windowID) {
            glutPushWindow();
            glutSetWindow(_windowID);
            glutSetWindowTitle(title.c_str());
            _windowTitle = title;
            glutPopWindow();
         }
         else {
            glutSetWindowTitle(title.c_str());
            _windowTitle = title;
         }
      }
   }


   void Window::setTimer(unsigned int delay, int value)
   {
      if (_windowID) {
         _timerPeriod = delay;

         if (glutGetWindow() != _windowID) {
            glutPushWindow();
            glutSetWindow(_windowID);
            glutTimerFunc(_timerPeriod, Window::windowTimer, value);
            glutPopWindow();
         }
         else {
            glutTimerFunc(_timerPeriod, Window::windowTimer, value);
         }
      }
   }


   bool Window::isExtensionSupported(const std::string& name) const
   {
      return glutExtensionSupported(name.c_str()) != 0;
   }


   void Window::windowClose()
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onDestroy();
            windows.remove(*i);
            break;
         }
      }
   }


   void Window::windowDisplay()
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onDisplay();
            break;
         }
      }
   }


   void Window::windowReshape(int w, int h)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onResize(w, h);
            break;
         }
      }
   }


   void Window::windowKeyDown(unsigned char key, int mx, int my)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onKeyDown(key, mx, my);
            break;
         }
      }
   }


   void Window::windowKeyUp(unsigned char key, int mx, int my)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onKeyUp(key, mx, my);
            break;
         }
      }
   }


   void Window::windowSKeyDown(int key, int mx, int my)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onKeyDown(key, mx, my);
            break;
         }
      }
   }


   void Window::windowSKeyUp(int key, int mx, int my)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onKeyUp(key, mx, my);
            break;
         }
      }
   }


   void Window::windowMouseEntry(int state)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            if (state == GLUT_ENTERED) {
               (*i)->onMouseEnter();
            }
            else {
               (*i)->onMouseExit();
            }

            break;
         }
      }
   }


   void Window::windowMouseMove(int mx, int my)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onMouseMove(mx, my);
            break;
         }
      }
   }


   void Window::windowMouseDrag(int mx, int my)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onMouseDrag(mx, my);
            break;
         }
      }
   }


   void Window::windowMousePress(int button, int state, int mx, int my)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            MouseWheelMap::iterator wheelIter = mouseWheels.find(button);

            if (wheelIter != mouseWheels.end()) {
               // Is there any reason to track up and down separately for wheels?
               if (state == GLUT_DOWN) {
                  windowMouseWheel(
                        wheelIter->second.first, wheelIter->second.second, mx, my);
               }
            }
            else {
               if (state == GLUT_DOWN) {
                  (*i)->onMouseDown(button, mx, my);
               }
               else {
                  (*i)->onMouseUp(button, mx, my);
               }
            }

            break;
         }
      }
   }


   void Window::windowMouseWheel(int wheel, int dir, int mx, int my)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onMouseWheel(wheel, dir, mx, my);
            break;
         }
      }
   }


   void Window::windowTimer(int value)
   {
      int window = glutGetWindow();

      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            (*i)->onTimer(value);
            break;
         }
      }
   }


   void Window::windowMenu(int state, int mx, int my)
   {
      int window = glutGetWindow();
      for (auto i = windows.begin(); i != windows.end(); ++i) {
         if ((*i)->_windowID == window) {
            if (state == GLUT_MENU_IN_USE) {
               (*i)->onMenuOpen(mx, my);
            }
            else {
               (*i)->onMenuClose(mx, my);
            }

            break;
         }
      }
   }


   void makeSoftWheel(int wheel, int up, int down)
   {
      mouseWheels[up] = std::make_pair(wheel, 1);
      mouseWheels[down] = std::make_pair(wheel, -1);
   }
}

